package com.server.controller;

import lombok.Data;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author: ywy
 * @date: 2022-11-13
 * @desc:
 */
@Data
class Person {
    String name;
    String age;

    @Override
    public String toString() {
        return "{" +
                "name:'" + name + '\'' +
                ", age:'" + age + '\'' +
                '}';
    }
}

@RestController
public class HomeController {

    @GetMapping("/")
    public String home(@RequestHeader(value = "Env", required = false, defaultValue = "prod") String env) {
        return "Home Page: " + env;
    }

    @GetMapping("/search")
    public String search(@RequestParam("kw") String kw) {
        return "Get Key Word:" + kw;
    }

    @PostMapping("/insert")
    public String insert(@RequestBody Person person) {
        return "Get Info:" + person;
    }

    @PutMapping("/upload")
    public String upload(MultipartFile file) {
        try {
            InputStream is = file.getInputStream();
            InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(ir);
            return "Get File:" + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return "Empty";
        }
    }
}
